#include "topsail.h"
#include "utils.h"
#include "error.h"
#include "wraps.h"

char *trim(char *str)
{
	char *pstart = str;
	char *pend = str + strlen(str) - 1;

	while (isspace(*pstart)) pstart++;
	while (isspace(*pend)) pend--;
	
	*(pend + 1) = 0;
	return pstart;
}

void sendline(int connfd, char *fmt, ...)
{
	char buf[LINE_BUF_SIZE];
	va_list ap;
	
	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);
	writen(connfd, buf, strlen(buf));
}

void sendmime(int connfd, int status, char *title, off_t length)
{
	time_t now;
	char timebuf[128];

	time(&now);
	strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&now));
	sendline(connfd, "HTTP/1.1 %d %s%s", status, title, CRLF);
	sendline(connfd, "Date: %s%s", timebuf, CRLF);
	sendline(connfd, "Server: %s/%s%s", SERVER_NAME, VERSION, CRLF);
	sendline(connfd, "Content-Length: %ld%s", length, CRLF);	
}

ssize_t writen(int fd, const void *vptr, size_t n)
{
	size_t nleft;
	ssize_t nwritten;
	const char *ptr;

	ptr = vptr;
	nleft = n;
	while (nleft > 0) {
		if ( (nwritten = write(fd, ptr, nleft)) <= 0) {
			if (nwritten < 0 && errno == EINTR)
				nwritten = 0;
			else
				err_sys(__FILE__, __LINE__, "write error");
		}
		nleft -= nwritten;
		ptr += nwritten;
	}
	return n;
}

void log_pid(char *pidfile)
{
	FILE *fp;
	char buf[LINE_BUF_SIZE];

	fp = Fopen(pidfile, "w", __FILE__, __LINE__);
	sprintf(buf, "%d", getpid());
	fputs(buf, fp);
	Fclose(fp, __FILE__, __LINE__);
}

/**
 * check file whether exist or not.
 *
 * return:
 * 	1: exit
 * 	0: no
 */
int file_exist(char *dir, char *file)
{
	struct stat buf;
	char pathname[LINE_BUF_SIZE];
	
	strcpy(pathname, dir);
	
	/* make sure: directory end of slash */
	if ( '/' != pathname[strlen(pathname) - 1])
		strcat(pathname, "/");

	strcat(pathname, file);

	if (lstat(pathname, &buf) == -1) {
		if (ENOENT == errno)
			return 0;
	}
	return 1;
}

